package handle

import (
	"server/game/define/helper"
	"server/game/handle/active"
	"server/game/model"

	"github.com/hwcer/cosgo/registry"
	"github.com/hwcer/yyds/context"
)

func init() {
	Register(&Exchange{})
}

/*
Gacha 抽卡扭蛋机
*/

type Exchange struct {
}

func (this *Exchange) Caller(node *registry.Node, handle *context.Context) interface{} {
	f := node.Method().(func(*Exchange, *context.Context) interface{})
	return f(this, handle)
}

// Code 使用兑换码
func (this *Exchange) Code(c *context.Context) any {
	code := c.GetString("code")
	if code == "" {
		return c.Error("code empty")
	}
	data := model.NewExchange(c.Uid(), code)
	tx := db.Find(data, data.OID)
	if tx.Error != nil {
		return tx.Error
	} else if tx.RowsAffected > 0 {
		return c.Errorf(helper.ErrorExchangeCodeNotExists, "exchange code exists")
	}

	mod := &active.Config{Code: code}
	err := mod.Init()
	if err != nil {
		return c.Errorf(helper.ErrorExchangeCodeConfigError, "exchange config error")
	}
	if mod.AType != active.ConfigATypeCode {
		return c.Error("not Exchange Code")
	}

	if _, err = mod.Verify(c.Player); err != nil {
		return err
	}

	c.Player.AddWithString(mod.Attach, ",")
	data.Update = c.Unix()
	if tx = db.Create(data); tx.Error != nil {
		return tx.Error
	}

	return true
}
